﻿using Quartz;
using quartz_service.JobTasks;
using quartz_service.Tools;

namespace quartz_service.JobModels
{
    /// <summary>
    /// Quartz 服务配置类
    /// </summary>
    public class QuartzHostedService(ISchedulerFactory schedulerFactory) : IHostedService
    {
        private readonly ISchedulerFactory schedulerFactory = schedulerFactory;
        private IScheduler? scheduler;

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            scheduler = await schedulerFactory.GetScheduler(cancellationToken);
            await scheduler.Start(cancellationToken);
 
            await ScheduleJobs(); // 按配置执行 Job
        }

        private async Task ScheduleJobs()
        {
            if (scheduler != null) 
            {
                var queryJob = JobBuilder.Create<QueryJob>()
                    .WithIdentity("QueryJob", "group1")
                    .Build();

                int? queryJobCorn = AppsettingsTool.Configuration?.GetValue<int>("JobCorns:QueryJob");
                var queryJobTrigger = TriggerBuilder.Create()
                    .WithIdentity("QueryJobTrigger", "group1")
                    .StartNow()
                    .WithSimpleSchedule(x => x
                        .WithIntervalInSeconds(queryJobCorn ?? 1)
                        .RepeatForever())
                    .Build();

                await scheduler.ScheduleJob(queryJob, queryJobTrigger); // 注册查询任务

                var addJob = JobBuilder.Create<AddJob>()
                    .WithIdentity("AddJob", "group1")
                    .Build();

                string? addJobCorn = AppsettingsTool.Configuration?.GetValue<string>("JobCorns:AddJob");
                var addJobTrigger = TriggerBuilder.Create()
                    .WithIdentity("AddJobTrigger", "group1")
                    .StartNow()
                    .WithCronSchedule(addJobCorn ?? "*/1 * * * * ?")
                    .Build();

                await scheduler.ScheduleJob(addJob, addJobTrigger); // 注册添加任务
            }
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            if (scheduler != null)
            {
                await scheduler.Shutdown(cancellationToken);
            }
        }
    }
}
